<!--
 * @Author: zhoulei0232
 * @Date: 2023-04-01 23:03:20
 * @LastEditTime: 2023-04-14 01:21:01
 * @LastEditors: zhoulei0232
 * @Description: 
-->
<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
      <el-form-item label="购买人QQ" prop="queryUserQQ">
        <el-input v-model="queryParams.queryUserQQ" placeholder="按QQ号码进行模糊查询" clearable style="width: 200px"
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="商品名称" prop="queryContent">
        <el-input v-model="queryParams.queryContent" placeholder="按商品名称进行模糊查询" clearable style="width: 200px"
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="审核状态" prop="queryStatus">
        <el-select v-model="queryParams.queryStatus" clearable placeholder="请选择">
          <el-option v-for="dict in approveStatusList" :key="dict.value" :label="dict.label"
            :value="dict.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="下单日期">
        <el-date-picker v-model="dateRange" value-format="YYYY-MM-DD" type="daterange" range-separator="-"
          start-placeholder="开始日期" end-placeholder="结束日期" @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="multiple" @click="handleAllApprove"
          v-hasPermi="['business:goods:edit']">批量审核</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['business:goods:remove']">删 除</el-button>
      </el-col>

      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="pageList" height="780px" @selection-change="handleSelectionChange"
      @sort-change="handleSortChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" type="index" width="100" />
      <el-table-column label="付款凭证" align="center" prop="src" width="320">
        <template #default="scope">
          <div class="invitation-image-list">
            <div v-for="(item, index) in scope.row.imagesList" :key="index">
              <el-image :key="index" style="width: 100px; height: 100px" :src="uploadShowUrl + item"
                :preview-teleported="true" :preview-src-list="[uploadShowUrl + item]" fit="contain" />
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="商品名称" align="center" prop="goodsName" width="150" :show-overflow-tooltip="true" />
      <el-table-column label="购买人QQ" align="center" prop="buyerQQ" width="150" />
      <el-table-column label="购买人昵称" align="center" prop="buyerQQNickName" width="150" />
      <el-table-column label="金额" align="center" prop="buyPrice" width="150" />
      <el-table-column label="购买数量" align="center" prop="buySum" width="150" />
      <el-table-column label="审核状态" align="center" prop="applyStatus" width="100">
        <template #default="scope">
          <dict-tag :options="approveStatusList" :value="scope.row.applyStatus" />
        </template>
      </el-table-column>

      <el-table-column label="下单时间" align="center" prop="buyDate" width="250">
        <template #default="scope">
          <span>{{
            parseTime(scope.row.buyDate, "{y}-{m}-{d} {h}:{m}:{s}")
          }}</span>
        </template>
      </el-table-column>


      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="280" :fixed="desk">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleApprove(scope.row)"
            v-hasPermi="['approve']">审核</el-button>
          <el-button link type="primary" icon="Edit" v-if="scope.row.applyStatus === 0" @click="handleUpdate(scope.row)"
            v-hasPermi="['edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['del']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改公告对话框 -->
    <el-dialog :title="title" v-model="open" width="780px" append-to-body>
      <el-form ref="noticeRef" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="审核意见" prop="approve">
              <el-radio-group v-model="form.approve">
                <el-radio v-for="dict in approveList" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="form.approve === '0'">
            <el-form-item label="驳回原因" prop="remark">
              <el-input type="textarea" :rows="2" placeholder="请输入驳回原因" v-model="form.remark">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="debouncedFn">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 修改 -->
    <el-dialog :title="title" v-model="open1" width="780px" append-to-body>
      <el-form ref="noticeRef1" :model="form1" :rules="rules1" label-width="120px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="商品名称" prop="goodsName">
              <el-input disabled placeholder="请输入商品名称" v-model="form1.goodsName">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="购买人QQ" prop="buyerQQ">
              <el-input placeholder="请输入购买人QQ" v-model="form1.buyerQQ">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="购买金额" prop="buyPrice">
              <el-input placeholder="请输入购买金额" v-model="form1.buyPrice">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="购买数量" prop="buySum">
              <el-input placeholder="请输入购买数量" v-model="form1.buySum">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="订单类型" prop="type">
              <el-select v-model="form1.type" clearable placeholder="请选择">
                <el-option v-for="item in typeList" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="平台" prop="platform">
              <el-input placeholder="请输入平台" v-model="form1.platform">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remarks">
              <el-input type="textarea" :rows="2" placeholder="请输入备注" v-model="form1.remarks">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="debouncedFn">确 定</el-button>
          <el-button @click="cancel1">取 消</el-button>
        </div>
      </template>
    </el-dialog>


  </div>
</template>

<script setup name="OrderExamine">
import { orderTypeEnums ,orderStatusEnums ,originEnums  } from "@/utils/enums"

import {
  listOrderBuy,
  deleteOrderBuy,
  updateOrderBuy,
  applyOrderBuy,
} from "@/api/goods/examine";

import useDesk from "@/hooks/useDesk";

import { useDebounceFn } from "@vueuse/core";

const { proxy } = getCurrentInstance();
// 图片上传地址
const uploadUrl = import.meta.env.VITE_APP_UPLOAD_API + "api/uploadCos/goods";
const uploadShowUrl = import.meta.env.VITE_APP_COS_API;
const imageUrl = ref("");
const dateRange = ref([]);
const dateRange1 = ref([]);
const pageList = ref([]);
const open = ref(false);
const open1 = ref(false);
const openExprot = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const loadingBtn = ref(false);

const { desk } = useDesk();

const approveStatusList = ref([
  {
    label: "已审核",
    value: 1,
    elTagClass: "",
    elTagType: "success",
  },
  {
    label: "待审核",
    value: 0,
    elTagClass: "",
    elTagType: "danger",
  },
]);

const approveList = ref([
  { label: "通过", value: 1 },
  { label: "不通过", value: 2 },
]);

const data = reactive({
    typeList:orderTypeEnums,
  form: {},
  form1: {},
  formExprot: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    queryUserName: undefined,
    queryContent: undefined,
    queryOrderIdIn: undefined,
    queryApprove: undefined,
  },
  rules: {
    approve: [
      { required: true, message: "审核状态不能为空", trigger: "change" },
    ],
  },
  rules1: {
    takeoutQQ: [{ required: true, message: "QQ不能为空", trigger: "blur" }],
    createTime: [{ required: true, message: " 不能为空", trigger: "change" }],
  },
  rulesExprot: {
    dateRange: [{ required: true, message: " 不能为空", trigger: "change" }],
  },
});

const { queryParams, form, rules, form1, rules1, formExprot, typeList } =
  toRefs(data);

/** 查询公告列表 */
function getList() {
  loading.value = true;
  let sendData = proxy.addDateRangeZL(
    queryParams.value,
    dateRange.value,
    "CreateTime"
  );
  sendData = proxy.addDateRangeZL(sendData, dateRange1.value, "UpdateTime");

  listOrderBuy(sendData).then((response) => {
    pageList.value = response.data.rows.map((item) => {
      let imagesList = [];
      if (item.src) {
        imagesList = item.src.split(",");
      }
      return {
        ...item,
        imagesList: imagesList,
      };
    });

    total.value = response.data.count;
    loading.value = false;
  });
}
/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}
/** 取消按钮 */
function cancel1() {
  open1.value = false;
  reset1();
}
/** 取消按钮 */
function cancelExprot() {
  openExprot.value = false;
  resetExprot();
}

/** 表单重置 */
function reset() {
  form.value = {
    approve: undefined,
    remark: undefined,
  };
  imageUrl.value = null;
  proxy.resetForm("noticeRef");
}
/** 表单重置1 */
function reset1() {
  form1.value = {};
  proxy.resetForm("noticeRef1");
}
function resetExprot() {
  formExprot.value = {};
  proxy.resetForm("exprotRef");
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  queryParams.value.queryUserName = undefined;
  queryParams.value.queryContent = undefined;
  queryParams.value.queryApprove = undefined;

  handleQuery();
}
/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 批量审核按钮操作 */
function handleAllApprove() {
  let approveId = ids.value;
  if (approveId.length === 0) {
    return;
  }
  form.value.id = approveId;
  open.value = true;
  title.value = "批量审批";
}
/**审核按钮操作 */
function handleApprove(row) {
  let approveId = row.id || ids.value;
  if (!Array.isArray(approveId)) {
    approveId = [approveId];
  }
  form.value.id = approveId;
  open.value = true;
  title.value = "审批";
}
/**修改按钮操作 */
function handleUpdate(row) {
  reset1();
  if (!row.id) {
    let arr = pageList.value.filter((item) => {
      return item.id == ids.value;
    });
    form1.value = {
      ...arr[0],
    };
  } else {
    form1.value = {
      ...row,
    };
  }

  open1.value = true;
  title.value = "修改";
}
// 防抖操作
const debouncedFn = useDebounceFn(
  () => {
    submitForm();
  },
  1000,
  { maxWait: 3000 }
);


/** 提交按钮 */
function submitForm() {
  if (title.value == "修改") {
    proxy.$refs["noticeRef1"].validate((valid) => {
      if (valid) {
        let sendData = {
          id: form1.value.id,
          buyerQQ: form1.value.buyerQQ,
          buyPrice: form1.value.buyPrice,
          buySum: form1.value.buySum,
          type:form1.value.type,
          platform: form1.value.platform,
          remarks: form1.value.remarks || "",
        };
        updateOrderBuy(sendData).then((response) => {
          proxy.$modal.msgSuccess("操作成功！");
          open1.value = false;
          getList();
        });
      }
    });
  } else {
    proxy.$refs["noticeRef"].validate((valid) => {
      if (valid) {
        let sendData = {
          ids: form.value.id,
          approve: form.value.approve,
          remark: form.value.remark || "",
        };

        if (sendData.approve === 1) {
          applyOrderBuy(sendData).then((response) => {
            proxy.$modal.msgSuccess("操作成功！");
            open.value = false;
            getList();
          });
        } else if (sendData.approve === 2) {
          applyOrderBuy(sendData).then((response) => {
            proxy.$modal.msgSuccess("操作成功！");
            open.value = false;
            getList();
          });

        }
      }
    });
  }
}
/** 删除按钮操作 */
function handleDelete(row) {
  let deleteId = row.id || ids.value;
  if (!Array.isArray(deleteId)) {
    deleteId = [deleteId];
  }

  proxy.$modal
    .confirm('是否确认删除购买人QQ为"' + row.buyerQQ + '"的数据项？')
    .then(function () {
      return deleteOrderBuy({ id: deleteId });
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => { });
}

// 排序
function handleSortChange(column) {
  let data1;
  if (column.order == "ascending") {
    data1 = "ASC";
  } else if (column.order == "descending") {
    data1 = "DESC";
  }
  if (!data1) {
    data.queryParams.orderName = undefined;
  } else {
    data.queryParams.orderName = column.prop;
  }
  data.queryParams.orderType = data1;
  getList();
}
// 打开导出弹框
function handleOpenExprot() {
  openExprot.value = true;
  title.value = "导出报表";
  resetExprot();
}
// 可以将此方法封装
function downFile(content, filename) {
  // 创建隐藏的可下载链接
  var eleLink = document.createElement("a");
  eleLink.download = filename;
  eleLink.style.display = "none";
  // 字符内容转变成blob地址
  var blob = new Blob([content]);
  eleLink.href = URL.createObjectURL(blob);
  document.body.appendChild(eleLink);
  // 触发点击
  eleLink.click();
  // 然后移除
  document.body.removeChild(eleLink);
  proxy.$modal.msgSuccess("操作成功");
}

getList();
</script>
<style lang="scss" scoped>
.color-blue {
  color: rgb(0, 119, 255);
  cursor: pointer;
}

.avatar-uploader {
  width: 200px;
  height: 300px;

  .avatar {
    width: 100%;
    height: 100%;
  }
}

.avatar-uploader :deep(.el-upload) {
  width: 100%;
  height: 100%;
  border: 1px dashed #dcdfe6;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader :deep(.el-upload:hover) {
  border-color: #409eff;
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

.invitation-image-list {
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
}
</style>
